package com.ls.lsqc.modules.sys.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lsqc.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.ls.lsqc.common.config.Global;
import com.ls.lsqc.common.persistence.AjaxDone;
import com.ls.lsqc.common.persistence.BaseEntity;
import com.ls.lsqc.common.persistence.Page;
import com.ls.lsqc.common.utils.ResourcesUtil;
import com.ls.lsqc.common.utils.StringUtils;
import com.ls.lsqc.common.web.BaseController;
import com.ls.lsqc.modules.sys.entity.Dict;
import com.ls.lsqc.modules.sys.entity.Finance;
import com.ls.lsqc.modules.sys.service.FinanceService;
import com.ls.lsqc.modules.sys.utils.DictUtils;
import freemarker.template.Configuration;
import groovy.util.ResourceException;

/**
 * @author 秦玉峰
 * @ClassName: FinanceSubController
 * @Description: 会计科目
 * @date 2017年3月31日 下午18:40:00
 */

@Controller
@RequestMapping(value = "${adminPath}/finance/subject")
public class FinanceSubController extends BaseController {

    @Autowired
    private FinanceService financeService;
    @Autowired
    Configuration freemarkerConfiguration;
    // 子项session
    private final String FINANCESUBLIST = "financeSubList";

    @ModelAttribute
    public Finance get(@RequestParam(required = false) String id) {
        // 判断id是否为空
        if (StringUtils.isNotBlank (id)) {
            // 执行查询语句 查询基本信息
            return financeService.get (Long.parseLong (id));
        } else {
            // 若为空，实例化
            return new Finance ();
        }
    }

    /**
     * @return url
     * @Title: 画面跳转用
     */
    @RequiresPermissions("finance:subject:view")
    @RequestMapping(value = {""})
    public String list(Model model) {
        // 款式类别
        List <Dict> financeList = DictUtils.getDictList (ResourcesUtil.getConfig ("financeList"));
        model.addAttribute ("financeList", financeList);
        // 画面跳转
        return "modules/sys/financeList";
    }

    /**
     * @param finance
     * @param request
     * @param response
     * @return searchList
     * @throws Exception
     * @Title: 画面检索
     * @Description: 查询页面
     */
    @RequiresPermissions("finance:subject:view")
    @RequestMapping(value = {"searchList"})
    @ResponseBody
    public String searchList(Finance finance, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Map <Object, Object> listMap = new HashMap <Object, Object> ();
        // ajax回调时使用的一览list名
        request.setAttribute (Global.LIST_NAME, "dict");
        // 画面取得的检索项目
        // 科目代码
        String itemCode = finance.getItemCode ();
        // 科目名称
        String itemName = finance.getItemName ();
        // 科目类别
        String itemCategory = finance.getItemCategory ();
        String strUri = request.getContextPath () + Global.getAdminPath ();
        // 拼接字符串供分页使用
        String searchParam = "&itemCodeHa=" + itemCode + "&itemName=" + itemName + "&itemCategory=" + itemCategory;
        // 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
        request.setAttribute (Global.SEARCH_PAEAM, searchParam);
        // 查询一览页面数据
        Page <Finance> page = financeService.findList (new Page <Finance> (request, response), finance);
        // 读取系统路径
        // 读取文件生成字符串
        String strHtml = "";
        Map <String, Object> map = new HashedMap ();
        map.put ("adminUri", strUri);
        map.put ("dicts", page.getList ());
        map.put ("pageNo", page.getPageNo ());
        map.put ("pageSize", page.getPageSize ());
        strHtml = FreeMarkerTemplateUtils
                .processTemplateIntoString (freemarkerConfiguration.getTemplate ("FinanceSub.ftl"), map);
        listMap.put ("dict", strHtml);
        listMap.put ("page", page.getHtml ());
        // ajax返回结果
        return renderString (response, listMap);
    }

    /**
     * 进入编辑页面
     *
     * @param finance
     * @param model
     * @return
     */
    @RequiresPermissions("finance:subject:edit")
    @RequestMapping(value = "form")
    public String form(Finance finance, Model model, HttpSession session) {
        // 款式类别
        List <Dict> financeList = DictUtils.getDictList (ResourcesUtil.getConfig ("financeList"));
        // 款式类别
        List <Dict> financeListTo = DictUtils.getDictList (ResourcesUtil.getConfig ("financeListTo"));
        // 新建判断 若不为null 编辑数据
        if (finance.getId () != null) {
            // 实力化子项实体类
            Finance dictSub = new Finance ();
            // 给子项实体类赋值（关联值——项目值）
            dictSub.setItemCode (finance.getItemCode ());
        } else {
            // 清空创建的子项
            session.setAttribute (FINANCESUBLIST, new ArrayList <Dict> ());
        }
        // 将实体类值赋给mvc model层返回jsp页面
        model.addAttribute ("finance", finance);
        model.addAttribute ("financeList", financeList);
        model.addAttribute ("financeListTo", financeListTo);
        // 返回页面地址
        return "modules/sys/financeEdit";
    }


    /**
     * 进入check页面
     *
     * @param itemCode
     * @return
     */
    @RequiresPermissions("finance:subject:edit")
    @ResponseBody
    @RequestMapping(value = "checkName")
    public String checkName(String itemCode, String itemCategory) {
        try {
            if (itemCode != null && financeService.getItemCodeFin (itemCode, itemCategory) == null) {
                // 返回true
                return "true";
            }
            // 数据值重名
            return "false";

        } catch (Exception e) {
            // 记录日志
            logger.error (e.getMessage (), e);
        }
        // 数据值重名
        return "true";
    }

    /**
     * 保存信息
     *
     * @param finance
     * @param response
     * @return
     * @throws ResourceException
     */
    @RequiresPermissions("finance:subject:edit")
    @RequestMapping(value = "save")
    @ResponseBody
    public String save(Finance finance, HttpServletResponse response) throws ResourceException {
        // 判断id是否为null （判断新建或修改）
        if (finance.getId () != null) {
            // 编辑数据
            // 判断数据是否删除
            Finance dictNew = get (finance.getId ().toString ());
            // 判断数据是否删除
            if (dictNew == null || BaseEntity.DEL_FLAG_DELETE.equals (dictNew.getDeleteFlag ())) {
                // 返回提示信息
                return renderString (response,
                        AjaxDone.error (getText ("This_record_has_been_deleted_or_modified_the_operation_failed")));
            }
            // 排他处理
            if (finance.getVersion () == get (finance.getId ().toString ()).getVersion ()) {
                // 版本号加1
                finance.setVersion (finance.getVersion () + 1);
            } else {
                // 返回提示信息
                return renderString (response,
                        AjaxDone.error (getText ("This_record_has_been_deleted_or_modified_the_operation_failed")));
            }
        } else {
            // 新建版本号赋值1
            finance.setVersion (1L);
        }
        // 保存基准数据及子项数据
        financeService.saveFinance (finance);
        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("dictSaveSuccess")));
    }

    /**
     * 进入查看页面
     *
     * @param finance
     * @param model
     * @return
     */
    @RequiresPermissions("finance:subject:view")
    @RequestMapping(value = "show")
    public String show(Finance finance, Model model) {
        model.addAttribute ("finance", finance);
        // 返回页面地址
        return "modules/sys/financeShow";
    }

    /**
     * 删除信息
     *
     * @param finance
     * @param response
     * @return
     */
    @RequiresPermissions("finance:subject:edit")
    @RequestMapping(value = "delete")
    public String delete(Finance finance, HttpServletResponse response) {
        try {
            // 执行逻辑删除方法
            financeService.deleteFinance (finance);
        } catch (Exception e) {
            // 记录日志
            logger.error (e.getMessage (), e);
            // 提示错误信息
            return renderString (response, AjaxDone.error (SystemMessageUtils.getMessageName ("System_error_please_contact_your_administrator")));
        }
        // 提示删除成功信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("dict_delete_success")));
    }
}